<template>
  <div class="waiting-quote-page">
    <!-- 顶部导航栏 -->
    <div class="header">
      <van-nav-bar>
        <template #left>
          <van-icon name="arrow-left" @click="handleGoBack" />
        </template>
        <template #title>
          <div class="header-tabs">
            <span class="tab active">等待报价</span>
            <span class="tab"  @click="toOrderPage">订单信息</span>
          </div>
        </template>
      </van-nav-bar>
    </div>

    <!-- 通知开启提示 -->
    <div class="notification-banner" v-if="!notificationEnabled">
      <van-icon name="volume-o" />
      <span class="notification-text">开启通知，及时获取订单进度！</span>
      <van-button size="small" type="primary" @click="enableNotification">立即开启</van-button>
      <van-icon name="cross" class="close-icon" @click="hideNotificationBanner" />
    </div>

    <!-- 等待报价主要内容 -->
    <div class="main-content">
      <h2 class="title">等待师傅报价</h2>
      <p class="subtitle">师傅预计在5-30分钟内报价，报价后请尽快选择师傅为您提供服务</p>
      
      <!-- 倒计时 -->
      <div class="countdown">
        <span class="countdown-label">距离报价截止还剩</span>
        <span class="countdown-time">{{ countdownDisplay }}</span>
      </div>
      
      <!-- 下单时间 -->
      <div class="order-time">
        <span>下单时间：{{ formatOrderTime }}</span>
      </div>
    </div>

    <!-- 保障卡 -->
    <div class="insurance-card">
      <div class="insurance-content">
        <h3>保障卡</h3>
        <p>支付订单后即可享受四大保障</p>
      </div>
      <van-button size="small" @click="viewInsuranceDetail">了解详情 ></van-button>
    </div>

    <!-- 安全提示 -->
    <div class="safety-warning">
      <div class="warning-content">
        <h3>您的安心 我们守护</h3>
        <h2>任何要求线下交易的行为</h2>
        <h2 class="warning-text">请立即举报</h2>
        <p>资金保障 | 赔付保险 | 免费售后</p>
      </div>
      <div class="warning-image">
        <!-- 这里可以添加警告图片 -->
        <div class="warning-icon">⚠️</div>
      </div>
    </div>

    <!-- 订单详情 -->
    <div class="order-details" v-if="orderInfo">
      <!-- 服务项目 -->
      <div class="service-item">
        <div class="item-image">
          <!-- 这里可以显示服务图片，暂时用占位符 -->
          <div class="placeholder-image"></div>
        </div>
        <div class="item-info">
          <h3>{{ orderInfo.itemType }}</h3>
          <span class="quantity">x1</span>
        </div>
      </div>

      <!-- 订单信息列表 -->
      <div class="order-info-list">
        <div class="info-item" v-if="orderType === 'curtain'">
          <span class="label">窗帘数量</span>
          <span class="value">{{ orderInfo.curtainQuantity || 1 }}个</span>
        </div>
        <div class="info-item">
          <span class="label">物品类型</span>
          <span class="value">{{ orderInfo.itemType }}</span>
        </div>
        <div class="info-item" v-if="orderType !== 'curtain'">
          <span class="label">维修类型</span>
          <span class="value">{{ parseRepairTypes(orderInfo.repairTypes) }}</span>
        </div>
        <div class="info-item" v-if="orderType === 'curtain'">
          <span class="label">安装高度</span>
          <span class="value">{{ orderInfo.installHeight || '未设置' }}</span>
        </div>
        <div class="info-item" v-if="orderType === 'curtain'">
          <span class="label">轨道类型</span>
          <span class="value">{{ orderInfo.trackType || '未设置' }}</span>
        </div>
        <div class="info-item" v-if="orderType === 'curtain'">
          <span class="label">墙面材质</span>
          <span class="value">{{ orderInfo.wallMaterial || '未设置' }}</span>
        </div>
        <div class="info-item" v-if="orderType === 'curtain'">
          <span class="label">轨道长度</span>
          <span class="value">{{ orderInfo.trackLength ? orderInfo.trackLength + 'm' : '未设置' }}</span>
        </div>
        <div class="info-item" v-if="orderType === 'curtain'">
          <span class="label">是否需要挂窗帘</span>
          <span class="value">{{ orderInfo.needHangCurtain || '未设置' }}</span>
        </div>
        <div class="info-item">
          <span class="label">物品图片</span>
          <div class="image-gallery" v-if="orderImages.length > 0">
            <van-image
              v-for="(image, index) in orderImages"
              :key="index"
              :src="image"
              fit="cover"
              width="60"
              height="60"
              class="order-image"
              @click="previewImages(index)"
            />
          </div>
          <span v-else class="no-image">暂无图片</span>
        </div>
        <div class="info-item">
          <span class="label">需求说明</span>
          <span class="value">{{ orderInfo.demandDescription || '无' }}</span>
        </div>
        <div class="info-item warranty-item">
          <van-icon name="shield-o" class="warranty-icon" />
          <span class="warranty-text">服务质保期30天</span>
          <span class="warranty-status">未开始 ></span>
        </div>
      </div>

      <!-- 展开/收起按钮 -->
      <div class="toggle-section" @click="toggleOrderDetails">
        <span>{{ showOrderDetails ? '收起' : '展开' }}</span>
        <van-icon :name="showOrderDetails ? 'arrow-up' : 'arrow-down'" />
      </div>

      <!-- 详细信息（可展开/收起） -->
      <div class="detailed-info" v-show="showOrderDetails">
        <div class="info-item">
          <span class="label">订单编号</span>
          <span class="value">{{ generateOrderNumber(orderInfo.orderid) }}</span>
          <van-button size="mini" @click="copyOrderNumber">复制</van-button>
        </div>
        <div class="info-item">
          <span class="label">下单时间</span>
          <span class="value">{{ formatOrderTime }}</span>
        </div>
        <div class="info-item">
          <span class="label">期望上门时间</span>
          <span class="value">{{ formatServiceTime }}</span>
        </div>
        <div class="info-item">
          <span class="label">服务地址</span>
          <div class="address-info">
            <p class="phone">{{ formatPhoneNumber }}</p>
            <p class="address-text">{{ orderInfo.address }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部安全提示 -->
    <div class="bottom-warning">
      <p>线下交易，纠纷难追款，意外难赔付，售后难保障</p>
      <van-button size="small" @click="viewDetails">查看详情</van-button>
    </div>

    <!-- 底部操作按钮 -->
    <div class="bottom-actions">
      <van-button icon="chat-o" @click="consultService">咨询</van-button>
      <van-button @click="cancelOrder">取消订单</van-button>
      <van-button @click="modifyOrder">修改订单</van-button>
      <van-button type="primary" @click="newQuoteNotification">新报价通知</van-button>
    </div>

    <!-- 图片预览 -->
    <van-image-preview
      v-model:show="showImagePreview"
      :images="orderImages"
      :start-position="previewStartIndex"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, computed, onUnmounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';
import {
  NavBar, Icon, Button, Cell, ImagePreview, Image as VanImage, showToast, showDialog
} from 'vant';
import { getOrderDetail, getCurtainOrderDetail } from '@/api';

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();

// 页面状态
const notificationEnabled = ref(false);
const showOrderDetails = ref(false);
const showImagePreview = ref(false);
const previewStartIndex = ref(0);

// 订单信息
const orderInfo = ref(null);
const orderType = ref('normal'); // 订单类型：normal 或 curtain
const countdownSeconds = ref(23 * 3600 + 57 * 60 + 39); // 23小时57分39秒的秒数

// 倒计时相关
const countdownTimer = ref(null);

// 计算属性
const countdownDisplay = computed(() => {
  const hours = Math.floor(countdownSeconds.value / 3600);
  const minutes = Math.floor((countdownSeconds.value % 3600) / 60);
  const seconds = countdownSeconds.value % 60;
  return `${hours.toString().padStart(2, '0')}时${minutes.toString().padStart(2, '0')}分${seconds.toString().padStart(2, '0')}秒`;
});

const formatOrderTime = computed(() => {
  if (!orderInfo.value?.createtime) return '';
  const date = new Date(orderInfo.value.createtime);
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
});

const formatServiceTime = computed(() => {
  if (!orderInfo.value?.serviceTime) return '未设置';
  
  try {
    const date = new Date(orderInfo.value.serviceTime);
    
    // 检查日期是否有效
    if (isNaN(date.getTime())) {
      console.error('无效的服务时间:', orderInfo.value.serviceTime);
      return '时间格式错误';
    }
    
    console.log('原始服务时间:', orderInfo.value.serviceTime);
    console.log('解析后的Date对象:', date);
    console.log('本地时间字符串:', date.toLocaleString());
    
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const startHour = date.getHours().toString().padStart(2, '0');
    const endHour = (date.getHours() + 2).toString().padStart(2, '0');
    
    const formattedTime = `${year}-${month}-${day} ${startHour}:00-${endHour}:00`;
    console.log('格式化后的服务时间:', formattedTime);
    
    return formattedTime;
  } catch (error) {
    console.error('格式化服务时间出错:', error);
    return '时间解析失败';
  }
});

const orderImages = computed(() => {
  if (!orderInfo.value?.pictures) return [];
  try {
    const pictures = JSON.parse(orderInfo.value.pictures);
    return Array.isArray(pictures) ? pictures : [];
  } catch (e) {
    return [];
  }
});

const formatPhoneNumber = computed(() => {
  const phone = userStore.phonenumber;
  console.log('获取用户手机号:', phone);
  
  if (!phone || phone.length < 7) {
    return '未设置手机号';
  }
  
  // 脱敏显示：前3位 + **** + 后4位
  if (phone.length === 11) {
    return phone.substring(0, 3) + '****' + phone.substring(7);
  } else {
    // 如果手机号长度不是11位，简单脱敏
    return phone.substring(0, 3) + '****';
  }
});

// 页面生命周期
onMounted(async () => {
  await loadOrderInfo();
  startCountdown();
});

onUnmounted(() => {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value);
  }
});

// 加载订单信息
const loadOrderInfo = async () => {
  try {
    const orderId = route.query.orderId;
    const type = route.query.type;
    orderType.value = type || 'normal';
    
    console.log('订单ID:', orderId, '订单类型:', orderType.value);
    
    if (!orderId) {
      showToast('订单ID不能为空');
      router.back();
      return;
    }

    // 根据订单类型调用不同的API
    let response;
    if (orderType.value === 'curtain') {
      response = await getCurtainOrderDetail(orderId);
    } else {
      response = await getOrderDetail(orderId);
    }
    
    if (response.code === 200) {
      orderInfo.value = response.data;
      console.log('获取到的订单信息:', orderInfo.value);
    } else {
      showToast(response.message || '获取订单详情失败');
      // 如果获取失败，使用模拟数据以便页面正常显示
      orderInfo.value = {
        orderid: orderId,
        itemType: orderType.value === 'curtain' ? '窗帘安装' : '储物柜',
        repairTypes: orderType.value === 'curtain' ? null : '["木质漆面修复"]',
        demandDescription: '测试订单',
        pictures: '[]',
        address: '北京北京市东城区东华门街道正义路2号北京市人民政府(旧址)',
        createtime: new Date().toISOString(),
        serviceTime: new Date(Date.now() + 6 * 3600 * 1000).toISOString(), // 6小时后的时间
        ...(orderType.value === 'curtain' ? {
          curtainQuantity: 1,
          installHeight: '2.7米以下',
          trackType: '直轨',
          wallMaterial: '混凝土墙',
          trackLength: 3.0,
          needHangCurtain: '需要'
        } : {})
      };
    }

  } catch (error) {
    console.error('加载订单信息失败:', error);
    showToast('加载订单信息失败');
  }
};

// 倒计时
const startCountdown = () => {
  countdownTimer.value = setInterval(() => {
    if (countdownSeconds.value > 0) {
      countdownSeconds.value--;
    } else {
      clearInterval(countdownTimer.value);
      showToast('报价时间已截止');
    }
  }, 1000);
};

// 工具函数
const parseRepairTypes = (repairTypesStr) => {
  try {
    const types = JSON.parse(repairTypesStr);
    return Array.isArray(types) ? types.join('、') : repairTypesStr;
  } catch (e) {
    return repairTypesStr;
  }
};

const generateOrderNumber = (orderId) => {
  // 直接使用订单ID作为订单编号，添加前缀P便于识别
  return `P${String(orderId).padStart(8, '0')}`;
};

// 事件处理函数
const handleGoBack = () => {
  router.back();
};

const enableNotification = () => {
  notificationEnabled.value = true;
  showToast('通知已开启');
};

const hideNotificationBanner = () => {
  notificationEnabled.value = true;
};

const viewInsuranceDetail = () => {
  router.push('/insurance');
};

const toggleOrderDetails = () => {
  showOrderDetails.value = !showOrderDetails.value;
};

const previewImages = (index) => {
  previewStartIndex.value = index;
  showImagePreview.value = true;
};

const copyOrderNumber = () => {
  const orderNumber = generateOrderNumber(orderInfo.value.orderid);
  // 复制到剪贴板的实现
  if (navigator.clipboard) {
    navigator.clipboard.writeText(orderNumber).then(() => {
      showToast('订单编号已复制');
    });
  } else {
    showToast('复制功能不支持');
  }
};

const viewDetails = () => {
  showDialog({
    title: '安全提示',
    message: '为了您的资金安全，请通过平台进行交易，避免线下私人交易。',
    confirmButtonText: '我知道了'
  });
};

const consultService = () => {
  showToast('咨询功能开发中');
};

const cancelOrder = () => {
  showDialog({
    title: '取消订单',
    message: '确定要取消这个订单吗？',
    showCancelButton: true,
    confirmButtonText: '确定取消',
    cancelButtonText: '再想想'
  }).then(() => {
    showToast('订单已取消');
    router.push('/home');
  }).catch(() => {
    // 用户取消了操作
  });
};

const modifyOrder = () => {
  // 根据订单类型传递不同的数据结构
  const baseOrderData = {
    orderId: orderInfo.value.orderid,
    isModify: true,
    address: orderInfo.value.address,
    serviceTime: orderInfo.value.serviceTime,
    itemType: orderInfo.value.itemType,
    demandDescription: orderInfo.value.demandDescription || '',
    pictures: orderInfo.value.pictures || '[]',
    provinceId: orderInfo.value.provinceId,
    cityId: orderInfo.value.cityId,
    fastestArrivalTime: orderInfo.value.fastestArrivalTime || 4
  };

  let orderData;
  let targetPath;

  if (orderType.value === 'curtain') {
    // 窗帘订单的数据
    orderData = {
      ...baseOrderData,
      curtainQuantity: orderInfo.value.curtainQuantity || 1,
      installHeight: orderInfo.value.installHeight || '',
      trackType: orderInfo.value.trackType || '',
      wallMaterial: orderInfo.value.wallMaterial || '',
      trackLength: orderInfo.value.trackLength || '',
      needHangCurtain: orderInfo.value.needHangCurtain || ''
    };
    targetPath = '/curtain-order-confirm';
  } else {
    // 普通订单的数据
    orderData = {
      ...baseOrderData,
      repairTypes: orderInfo.value.repairTypes || '[]'
    };
    targetPath = '/confirm-order';
  }
  
  console.log('修改订单 - 传递的数据:', orderData);
  console.log('订单类型:', orderType.value);
  console.log('目标路径:', targetPath);
  
  // 确保地址信息不为空
  if (!orderData.address || orderData.address.trim() === '') {
    console.warn('地址信息为空，将使用默认值');
    orderData.address = '地址信息缺失，请重新选择';
  }
  
  router.push({
    path: targetPath,
    query: {
      isModify: 'true',
      orderData: encodeURIComponent(JSON.stringify(orderData))
    }
  });
};




const toOrderPage = () => {
  router.push("/orderPage")}

const newQuoteNotification = () => {
  showToast('新报价通知已开启');
};
</script>

<style scoped>
.waiting-quote-page {
  background-color: #f8f8f8;
  min-height: 100vh;
  padding-bottom: 80px;
}

/* 顶部导航 */
.header {
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-tabs {
  display: flex;
  gap: 20px;
}

.tab {
  padding: 8px 16px;
  font-size: 16px;
  color: #666;
  border-bottom: 2px solid transparent;
}

.tab.active {
  color: #00bcd4;
  border-bottom-color: #00bcd4;
}

/* 通知横幅 */
.notification-banner {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  background-color: #e1f5fe;
  color: #0277bd;
  font-size: 14px;
}

.notification-text {
  flex: 1;
}

.close-icon {
  font-size: 16px;
  cursor: pointer;
}

/* 主要内容 */
.main-content {
  background-color: #fff;
  padding: 24px 16px;
  text-align: center;
  margin-bottom: 12px;
}

.title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.subtitle {
  font-size: 14px;
  color: #666;
  margin-bottom: 20px;
  line-height: 1.5;
}

.countdown {
  margin-bottom: 16px;
}

.countdown-label {
  font-size: 14px;
  color: #666;
  margin-right: 8px;
}

.countdown-time {
  font-size: 18px;
  font-weight: bold;
  color: #ff6b35;
}

.order-time {
  font-size: 14px;
  color: #999;
}

/* 保障卡 */
.insurance-card {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  margin-bottom: 12px;
  background: linear-gradient(135deg, #1976d2 0%, #42a5f5 100%);
  color: white;
  border-radius: 8px;
  margin: 12px 16px;
}

.insurance-content h3 {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 4px;
}

.insurance-content p {
  font-size: 14px;
  opacity: 0.9;
}

/* 安全提示 */
.safety-warning {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 16px;
  margin: 12px 16px;
  background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
  border-radius: 8px;
}

.warning-content h3 {
  font-size: 14px;
  color: #1976d2;
  margin-bottom: 4px;
}

.warning-content h2 {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 2px;
}

.warning-text {
  color: #f44336 !important;
}

.warning-content p {
  font-size: 12px;
  color: #666;
  margin-top: 8px;
}

.warning-image {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 80px;
  height: 80px;
}

.warning-icon {
  font-size: 48px;
}

/* 订单详情 */
.order-details {
  background-color: #fff;
  margin: 12px 16px;
  border-radius: 8px;
  overflow: hidden;
}

.service-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.item-image {
  width: 60px;
  height: 60px;
  margin-right: 12px;
}

.placeholder-image {
  width: 100%;
  height: 100%;
  background-color: #f0f0f0;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 12px;
}

.item-info {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item-info h3 {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.quantity {
  font-size: 14px;
  color: #666;
}

.order-info-list {
  padding: 0 16px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 12px 0;
  border-bottom: 1px solid #f8f8f8;
}

.info-item:last-child {
  border-bottom: none;
}

.label {
  font-size: 14px;
  color: #666;
  white-space: nowrap;
  margin-right: 16px;
}

.value {
  font-size: 14px;
  color: #333;
  text-align: right;
  flex: 1;
  word-break: break-all;
}

.image-gallery {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.order-image {
  border-radius: 4px;
  cursor: pointer;
}

.no-image {
  font-size: 14px;
  color: #999;
}

.warranty-item {
  align-items: center;
  background-color: #f8f9fa;
  padding: 12px;
  border-radius: 4px;
  border: none;
}

.warranty-icon {
  color: #4caf50;
  font-size: 16px;
  margin-right: 8px;
}

.warranty-text {
  color: #4caf50;
  font-size: 14px;
  flex: 1;
  text-align: left;
}

.warranty-status {
  font-size: 14px;
  color: #999;
}

.toggle-section {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 4px;
  padding: 12px;
  background-color: #f8f8f8;
  cursor: pointer;
  font-size: 14px;
  color: #666;
}

.detailed-info {
  padding: 0 16px 16px;
}

.address-info .phone {
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
}

.address-info .address-text {
  font-size: 14px;
  color: #666;
  line-height: 1.4;
}

/* 底部警告 */
.bottom-warning {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: #fff3e0;
  margin: 12px 16px;
  border-radius: 4px;
  font-size: 12px;
  color: #f57c00;
}

/* 底部操作 */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  gap: 8px;
  padding: 12px 16px;
  background-color: #fff;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
}

.bottom-actions .van-button {
  flex: 1;
  height: 44px;
  font-size: 14px;
}

.bottom-actions .van-button:first-child {
  background-color: #f8f8f8;
  color: #666;
  border: 1px solid #e0e0e0;
}

.bottom-actions .van-button:nth-child(2),
.bottom-actions .van-button:nth-child(3) {
  background-color: #fff;
  color: #333;
  border: 1px solid #e0e0e0;
}

.bottom-actions .van-button:last-child {
  background-color: #00bcd4;
  color: #fff;
  border: 1px solid #00bcd4;
}
</style>
